﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace EcoSystem
{
    public class DemoAppService : IDemoAppService
    {
        private readonly IScriptAppService service;

        public DemoAppService(IScriptAppService service)
        {
            this.service = service;
            
        }

        /// <summary>
        /// 初始化 
        /// </summary>
        /// <returns></returns>

        public async Task InitAsync()
        {
            //注册方法名 - sum
            string methodName = "sum";
            string methodContent = "return a + b;";
            string[] argNames = new string[] { "a", "b" };
            service.RegisterMethod(methodName, methodContent, argNames);

            //注册方法名 - jsonToString
            string methodName2 = "jsonToString";
            string methodContent2 = "return JSON.stringify(items);";
            string[] argNames2 = new string[] { "items" };
            service.RegisterMethod(methodName2, methodContent2, argNames2);

            //注册方法名 - stringToObject
            string methodName3 = "stringToObject";
            string methodContent3 =
                " let result = JSON.parse(text);\r\n" +
                " return JSON.stringify(result);";
            string[] argNames3 = new string[] { "text" };
            service.RegisterMethod(methodName3, methodContent3, argNames3);
            await Task.CompletedTask;
        }

        /// <summary>
        /// 调用 
        /// </summary>
        /// <returns></returns>
        public async Task<dynamic> TestAsync()
        {
            Dictionary<string, object> result = new Dictionary<string, object>();


            //执行方法 - sum
            var result1 = service.ExecuteMethod<int>("sum", new Dictionary<string, object> {
                { "a", 1 },
                { "b", 2 }
            });

            //执行方法 - jsonToString
            var items = new List<string>() { "a1", "a2", "a3" };
            var result2 = service.ExecuteMethod<string>("jsonToString", new Dictionary<string, object> { { "items", items } });

            //执行方法 - stringToObject
            var str = "{\"id\":1,\"age\":30,\"address\":\"贵阳\"}";
            var result3 = service.ExecuteMethod<object>("stringToObject", new Dictionary<string, object> { { "text", str } });

            result.Add("sum", result1);
            result.Add("jsonToString", result2);
            result.Add("stringToObject", result3);

            return await Task.FromResult(result);
        }
    }
}
